(function($){
    
    $.action = {
    
        "set-models" : function(res){
            var data = [];
            for ( var i = 0; i < res.childNodes.length; i++ ){
                var item = res.childNodes.item(i);
                if (item.nodeType == res.ELEMENT_NODE){
                    data.push(item.textContent);
                }
            }
            $("input[name=car-model]").typeahead({
                source: data,
                items: 8
            });
        },
        
        "set-categories" : function(res){
            var data = [];
            for ( var i = 0; i < res.childNodes.length; i++ ){
                var item = res.childNodes.item(i);
                if (item.nodeType == res.ELEMENT_NODE){
                    data.push(item.textContent);
                }
            }
            $("input[name=category]").typeahead({
                source: data,
                items: 8
            });
        },
        
        "update-goods-table" : function(res){
            $('#table-holder').html("");
            for ( var i = 0; i < res.childNodes.length; i++ ){
                var item = res.childNodes.item(i);
                if (item.nodeType == res.ELEMENT_NODE){
                    $('#table-holder').append(item);
                }
            }
            /*$('#goods-list').dataTable({
                "sDom": "<'row'<'span6'l><'span6'f>r>t<'row'<'span6'i><'span6'p>>"
            });*/
        },
        
        "exception" : function(res){
            alert ($(res).text());   
        }
        
    };
     
    $.controller = {
    
        request : function (req) {
            for (var i in req) {
                $.post("/apps/avto-magazin/api/" + i, $.param(req[i]), response); 
            }
        }
     
    };
     
    function response(res) {
        var doc = res.documentElement;
        var action = $.action[doc.tagName];
        if (action) {
            var req = action(doc);
            if (req) {
                $.controller.request(req);
            }
        }
        
    }
     
    $("form").ajaxForm({
        type : "post",
        dataType : "xml",
        success : function(){
            $('form').resetForm();
            $.controller.request({"goods-list-in-table":""});
        }
    });
   
})(jQuery);
